package com.itheima.controller;

import com.itheima.common.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 实现文件操作的类
 */

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String path;

    //文件上传，作为服务器就是获取并储存文件
    @PostMapping("/upload")
    public R upload(MultipartFile file){
        //获取随机名字，防止文件名重复导致覆盖
        String uuid = UUID.randomUUID().toString();
        //获取源文件的后缀
        String originalFilename = file.getOriginalFilename();
        int lasted = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(lasted);
        //拼接得到文件
        String fileName=uuid+suffix;
        System.out.println(fileName);

        //防止path路径不存在导致的错误
        File file1 = new File(path);
        if(!file1.exists()){
            //创建这样一个文件夹
            file1.mkdirs();
        }

        try {
            //将文件存到服务器
            file.transferTo(new File(path + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //反正以后有用，说一堆不知所云
        //就是，前端会立刻根据返回的名字/common/download?name=..  发送请求
        return R.success(fileName);
    }

    //文件下载，作为服务器就是将文件传给前端
    //GET /common/download?name=ok HTTP/1.1
    @GetMapping("/download")                //为了获取输出流
    public void download(String name, HttpServletResponse response){
        //1.在服务器读取文件
        // 2.向客户端写文件


        try {
            //获取输入流
            FileInputStream fis = new FileInputStream(new File(path + name));
            //获取输出流
            ServletOutputStream outputStream = response.getOutputStream();

            int read=0;
            byte[] bytes=new byte[1024];

            //设置文件格式
            response.setContentType("image/jpeg");

            //         读取文件
            while ((read=fis.read(bytes))!=-1){
                //写文件
                outputStream.write(bytes,0,read);
                outputStream.flush();
            }

            //关闭资源
            fis.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
